<?php

// @formatter:off
/**
 * @file WCParserBehaviorDELAYEDLOAD.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: WCParserBehaviorDELAYEDLOAD.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/includes/mvc/WCParserBehaviorDELAYEDLOAD.php $
 */
// @formatter:on

/**
 * @class WCParserBehaviorDELAYEDLOAD This is a specific behavior that returns a variables
 * value. When it's used it looks like:
 * @code
 * <:DELAYEDLOAD:/>name<::/>
 * @endcode
 */
class WCParserBehaviorDELAYEDLOAD extends WCParserBehavior {
	/**
	 * This method perform a check of the object, sets the current status
	 * (variable $this->_ok) and return it.
	 *
	 * @return boolean Returns the current status after a check.
	 */
	public function check() {
		//
		// A DELAYEDLOAD behavior must belong to a parser node.
		if($this->_node) {
			//
			// Loading node's children.
			$children = $this->_node->children();
			//
			// A DELAYEDLOAD behavior requires at least one child
			// belonging to its parser node.
			if(!isset($children[0])) {
				//
				// Its parser node has no children. Error message
				// is set and the internal status becomes false.
				$this->_errorMsg = "node needs at least one child";
				$this->_ok = false;
//			} elseif(!is_string($children[0])) {
//				//
//				// The first child of node is not a string and it
//				// cannot be considered as a name. Error message
//				// is set and the internal status becomes false.
//				$this->_errorMsg = "node's first child is not an url";
//				$this->_ok = false;
			} else {
				//
				// At this point, everything checks out.
				$this->_ok = true;
				$this->_errorMsg = "Ok";
			}
		} else {
			//
			// Behavior's node is not present. Error message is set
			// and the internal status becomes false.
			$this->_errorMsg = "DELAYEDLOAD node is not set";
			$this->_ok = false;
		}
		//
		// Returning current object status.
		return $this->isOk();
	}
	/**
	 * This method actually performs the function represented based on its
	 * node's data.
	 *
	 * @return string Returns the value of a variable using node's contents as
	 * a name. Otherwise, returns false.
	 */
	public function get() {
		//
		// Setting the default value to be returned.
		$out = false;
		//
		// DELAYEDLOAD behavior will only be evaluated when this behavior has no
		// issues.
		if($this->isOk()) {
			$out = "";
			//
			// Loading parameters.
			$params = $this->_node->params();
			//
			// Creating a shortcut to the parser.
			$parser = $this->_node->parser();
			//
			// Loading node's children.
			$children = $this->_node->children();
			//
			// 
			$content = $this->_node->parseChildren();
			//
			// Asking the parser for this variable.
			if(strtolower($content) == "header") {
				global $wcPaths;
				global $wcROOTURI;

				$file = "{$wcROOTURI}/{$wcPaths["mvc"]["include-uri"]}/WCParserBehaviorDELAYEDLOAD.header.js";

				$out = "<script type=\"text/javascript\" src=\"{$file}\">\n";
				$out.= "\tconsole.log(\"Unable to load '{$file}'\");\n";
				$out.= "</script>";
//			} elseif(strtolower($content) == "trigger") {
//				global $wcPaths;
//
//				$file = "{$wcPaths["mvc"]["include-uri"]}/WCParserBehaviorDELAYEDLOAD.trigger.js";
//
//				$out = "<script type=\"text/javascript\" src=\"{$file}\">\n";
//				$out.= "\tconsole.log(\"Unable to load '{$file}'\");\n";
//				$out.= "</script>";
			} else {
				//
				// jQuery direct access.
				$id = isset($params["id"]) ? $params["id"] : "";
				//
				// jQuery access by selector.
				$selector = isset($params["selector"]) ? $params["selector"] : "";
				if(!isset($params["noauto"])) {
					$content = $this->appendAutoParams($content);
				}

				if(!$id && !$selector) {
					$out = "<script type=\"text/javascript\">";
					$out.= "console.log(\"There's no tag id nor selector specification where to load '{$content}'\");";
					$out.= "</script>";
				} elseif(!$content && !isset($params["!"])) {
					$out = "<script type=\"text/javascript\">";
					$out.= "console.log(\"There's nothing to load\");";
					$out.= "</script>";
				} elseif(!$content && isset($params["!"])) {
					$out = "";
				} else {
					//
					// Converting direct accessor into a
					// selector.
					if(!$selector) {
						$selector = "#{$id}";
					}
					$loadingText = "";
					if(isset($params["loading"])) {
						if("{$params["loading"] }" == "img") {
							global $wcDefaults;
							$loadingText = "<img src=\"{$wcDefaults["loading"]}\"/>";
						} else {
							$loadingText = "loading...";
						}
					}
					$out = "<script type=\"text/javascript\">";
					$out.= "$(document).ready(function(){";
					$out.= "$(\"{$selector}\").wcGetDelayedLoad(\"{$content}\");";
					$out.= "});</script>";
					$out.= $loadingText;
				}
			}
			//
			// When there's a parameter 'padding' set,
			// every line must be indented with as
			// many TAB characters as the number given
			// by the parameter 'padding'.
			if(isset($params["padding"])) {
				//
				// General spacer.
				$padding = str_repeat("\t", $params["padding"]);
				//
				// When the parameter 'nfl' is
				// given, the first line is not
				// indented.
				$out = (isset($params["nfl"]) ? "" : $padding).str_replace("\n", "\n".$padding, $out);
			}
		}
		//
		// Returning evaluation results.
		return $out;
	}
	//
	// Protected methods.
	protected function appendAutoParams($url) {
		$params = array();

		foreach(array("action", "collection", "comic", "directory", "group", "image", "rule", "tag") as $key) {
			if(isset($_REQUEST[$key])) {
				$params[] = "{$key}={$_REQUEST[$key]}";
			}
		}

		return $url.(strpos($url, "?") !== false ? "&" : "?").implode("&", $params);
	}
}
